package com.example.validproject.config;


import com.example.validproject.exception.BusinessException;
import com.example.validproject.protocol.BaseErrorCode;
import com.example.validproject.protocol.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.NativeWebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author ：johnstom
 * @Date ：Created in 10:44 AM 2020/04/06
 */
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

  /*@InitBinder
  public void initBinder(WebDataBinder binder) {
  }*/

  /**
   * 参数校验异常
   *
   * @param e Exception
   * @return Object
   */
  @ExceptionHandler(MethodArgumentNotValidException.class)
  @ResponseStatus(HttpStatus.OK)
  public Result processValidateException(MethodArgumentNotValidException e) {
    StringBuffer sbf = new StringBuffer();
    List<ObjectError> errors = e.getBindingResult().getAllErrors();
    if (!CollectionUtils.isEmpty(errors)) {
      for (int i = 0; i <errors.size() ; i++) {
        if (i == errors.size() - 1) {
          sbf.append(errors.get(i).getDefaultMessage());
        } else {
          sbf.append(errors.get(i).getDefaultMessage()+ "、");
        }
      }
    }
    return Result.failure(BaseErrorCode.PARAM_ERROR,sbf.toString());
  }

  @ExceptionHandler(Exception.class)
  @ResponseStatus(HttpStatus.OK)
  public Object exception(NativeWebRequest request, Exception e, HttpServletRequest req) {
    String url = req.getRequestURL().toString();
    log.error(url);
    BusinessException ex = new BusinessException(BaseErrorCode.INTERNAL_SERVER_ERROR);
    log.warn("Exception: code->{}, message->{}", ex.getErrorCode(),e.getMessage(), e);
    return Result.failure(ex);
  }

  @ExceptionHandler({BusinessException.class})
  @ResponseStatus(HttpStatus.OK)
  public Object processCustomSdkException(BusinessException e, HttpServletRequest request) {
    log.warn("BusinessException: code->{}, message->{}", e.getErrorCode(),e.getMessage(), e);
    return Result.failure(e);
  }

}
